<template>
	<el-form size="large" class="login-content-form" :model="state.ruleForm" :rules="loginRules" ref="formRef">
		<!-- 用户名称 -->
		<el-form-item class="login-animation1" prop="userName">
			<el-input :placeholder="$t('message.account.accountPlaceholder1')" v-model="state.ruleForm.userName"
				clearable autocomplete="off">
				<template #prefix>
					<el-icon class="el-input__icon">
						<User />
					</el-icon>
				</template>
			</el-input>
		</el-form-item>
		<!-- 密码 -->
		<el-form-item class="login-animation2" prop="password">
			<el-input :type="state.isShowPassword ? 'text' : 'password'"
				:placeholder="$t('message.account.accountPlaceholder2')" v-model="state.ruleForm.password"
				autocomplete="off" @input="state.ruleForm.password = state.ruleForm.password.replace(/[^\d]/g, '')">
				<template #prefix>
					<el-icon class="el-input__icon">
						<Lock />
					</el-icon>
				</template>
				<template #suffix>
					<i class="iconfont el-input__icon login-content-password"
						:class="state.isShowPassword ? 'icon-yincangmima' : 'icon-xianshimima'"
						@click="state.isShowPassword = !state.isShowPassword">
					</i>
				</template>
			</el-input>
		</el-form-item>
		<!-- 登录按钮 -->
		<el-form-item class="login-animation4">
			<el-button type="primary" class="login-content-submit" round v-waves @click="handleLogin"
				:loading="state.loading.signIn">
				<span>{{ $t('message.account.accountBtnText') }}</span>
			</el-button>
		</el-form-item>
	</el-form>
</template>

<script setup lang="ts" name="loginAccount">
import { reactive, computed, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElForm } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import { Session } from '/@/utils/storage';
import { formatAxis } from '/@/utils/formatTime';
import { NextLoading } from '/@/utils/loading';
import { useLoginApi } from '/@/api/login/index';
import { useUserInfo } from '/@/stores/userInfo';
import { User, Lock } from '@element-plus/icons-vue';

const { t } = useI18n();
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const { isRequestRoutes } = themeConfig;
const route = useRoute();
const router = useRouter();
const formRef = ref<InstanceType<typeof ElForm>>();

const state = reactive({
	isShowPassword: false,
	ruleForm: {
		userName: '',
		password: '',
	},
	loading: {
		signIn: false,
	},
});

const loginRules = {
	userName: [
		{ required: true, message: '请输入账号', trigger: 'change' },
	],
	password: [
		{ required: true, message: '请输入密码', trigger: 'change' },
		{ min: 6, message: '密码长度至少 6 位', trigger: 'change' },
	],
};

const currentTime = computed(() => {
	return formatAxis(new Date());
});

// 登录按钮
const handleLogin = async () => {
	await formRef.value?.validate(async (valid) => {
		if (valid) {
			state.loading.signIn = true;
			try {
				const res = await useLoginApi().signIn({
					account: state.ruleForm.userName,
					password: state.ruleForm.password,
				});

				// 关键修复：先设置用户信息
				useUserInfo().setUserInfos(res);

				// 关键修复：设置认证状态和密码（必须在路由初始化之前）
				Session.set('isAuthenticated', 'true');
				Session.set('loginPassword', state.ruleForm.password);

				// 清除可能的锁屏状态
				localStorage.removeItem('isLocked');
				localStorage.removeItem('attemptedPath');

				// 初始化路由
				let isNoPower = false;
				if (isRequestRoutes) {
					const result = await initBackEndControlRoutes();
					isNoPower = typeof result === 'boolean' ? result : result.isNoPower;
				} else {
					await initFrontEndControlRoutes();
				}

				// 登录成功处理
				await signInSuccess(isNoPower);

			} catch (error) {
				state.loading.signIn = false;
				console.error('登录失败:', error);
				ElMessage.error(`${(error as { message: string }).message}`);
			}
		}
	});
};

// 登录成功后的处理函数
const signInSuccess = async (isNoPower: boolean = false) => {
	const currentTimeInfo = currentTime.value;

	// 如果有权限问题，跳转到401页面
	if (isNoPower) {
		router.push('/401');
		ElMessage.warning('您没有权限访问系统');
		return;
	}

	// 处理重定向或默认跳首页
	let redirectPath = '/';
	let queryParams = {};

	if (route.query?.redirect) {
		redirectPath = route.query.redirect as string;
		if (route.query?.params) {
			try {
				queryParams = JSON.parse(route.query.params as string);
			} catch (e) {
				console.warn('解析路由参数失败:', e);
			}
		}
	}

	// 关键修复：使用replace而不是push，避免浏览器历史记录问题
	await router.replace({
		path: redirectPath,
		query: queryParams
	});

	// 登录成功提示
	ElMessage.success(`登录成功, ${currentTimeInfo}`);

	// 关闭加载状态
	state.loading.signIn = false;

	// 延迟加载进度条，确保页面跳转完成
	setTimeout(() => {
		NextLoading.done();
	}, 300);
};
</script>

<style scoped lang="scss">
.el-input--large {
	margin-top: 3px;
}

.login-content-form {
	margin-top: 20px;

	@for $i from 1 through 4 {
		.login-animation#{$i} {
			opacity: 0;
			animation-name: fadeIn;
			animation-duration: 0.5s;
			animation-fill-mode: forwards;
			animation-delay: calc($i/10) + s;
		}
	}

	.login-content-password {
		display: inline-block;
		width: 20px;
		cursor: pointer;

		&:hover {
			color: #f56c6c;
		}
	}

	.login-content-submit {
		width: 100%;
		letter-spacing: 2px;
		font-weight: 500;
		margin-top: 15px;
	}

	.el-form-item {
		margin-bottom: 15px;

		.el-input {
			width: 100%;

			.el-input__prefix {
				color: #999;
			}

			.el-input__inner {
				height: 40px;
				border-radius: 0;
				border: 1px solid #dcdcdc;
				padding-left: 35px;
				font-size: 14px;

				&::placeholder {
					color: #999;
				}

				&.is-error {
					border-color: #f56c6c;
				}
			}
		}

		.el-form-item__error {
			color: #f56c6c;
			font-size: 12px;
			margin-top: 5px;
		}
	}

	.el-button--primary {
		width: 100%;
		height: 40px;
		background-color: #409eff;
		border-color: #409eff;
		border-radius: 0;
		font-size: 16px;

		&:hover {
			background-color: #66b1ff;
			border-color: #66b1ff;
		}
	}
}

@keyframes fadeIn {
	from {
		opacity: 0;
		transform: translateY(10px);
	}

	to {
		opacity: 1;
		transform: translateY(0);
	}
}
</style>